#!/bin/bash
# ========================================
# 若依系统一键启动脚本
# ========================================

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m'

# 项目配置
APP_NAME="ruoyi-admin.jar"
APP_PORT=8080
DB_NAME="ry-vue"
DB_USER="root"
DB_PASS="123"

# 打印消息
print_msg() {
    echo -e "${2}${1}${NC}"
}

# 打印标题
print_title() {
    echo ""
    print_msg "=========================================" "$CYAN"
    print_msg "  $1" "$CYAN"
    print_msg "=========================================" "$CYAN"
    echo ""
}

# 显示菜单
show_menu() {
    clear
    print_msg "╔════════════════════════════════════════╗" "$GREEN"
    print_msg "║    若依系统 - 一键管理脚本             ║" "$GREEN"
    print_msg "╚════════════════════════════════════════╝" "$GREEN"
    echo ""
    print_msg "请选择操作：" "$BLUE"
    echo ""
    print_msg "  [1] 🚀 一键部署（数据库+后端+前端）" "$YELLOW"
    print_msg "  [2] 📊 初始化数据库" "$YELLOW"
    print_msg "  [3] 🔨 编译后端" "$YELLOW"
    print_msg "  [4] 🎨 构建前端" "$YELLOW"
    print_msg "  [5] ▶️  启动后端" "$YELLOW"
    print_msg "  [6] ⏸️  停止后端" "$YELLOW"
    print_msg "  [7] 🔄 重启后端" "$YELLOW"
    print_msg "  [8] 📝 查看日志" "$YELLOW"
    print_msg "  [9] 🧪 测试系统" "$YELLOW"
    print_msg "  [0] 👋 退出" "$YELLOW"
    echo ""
}

# 检查MySQL
check_mysql() {
    if ! command -v mysql &> /dev/null; then
        print_msg "❌ MySQL客户端未安装" "$RED"
        return 1
    fi
    
    if ! mysql -h localhost -u"$DB_USER" -p"$DB_PASS" -e "SELECT 1;" &> /dev/null; then
        print_msg "❌ 无法连接MySQL数据库" "$RED"
        return 1
    fi
    
    return 0
}

# 初始化数据库
init_database() {
    print_title "📊 初始化数据库"
    
    if ! check_mysql; then
        print_msg "请检查MySQL服务和配置" "$RED"
        return 1
    fi
    
    print_msg "正在创建数据库..." "$BLUE"
    mysql -h localhost -u"$DB_USER" -p"$DB_PASS" -e "CREATE DATABASE IF NOT EXISTS \`$DB_NAME\` DEFAULT CHARACTER SET utf8mb4;"
    
    if [ ! -f "sql/complete_schema.sql" ]; then
        print_msg "❌ SQL文件不存在: sql/complete_schema.sql" "$RED"
        return 1
    fi
    
    print_msg "正在导入数据表..." "$BLUE"
    mysql -h localhost -u"$DB_USER" -p"$DB_PASS" "$DB_NAME" < sql/complete_schema.sql
    
    # 验证
    TABLE_COUNT=$(mysql -h localhost -u"$DB_USER" -p"$DB_PASS" "$DB_NAME" \
        -e "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='$DB_NAME';" \
        2>/dev/null | tail -n 1)
    
    print_msg "✅ 数据库初始化完成！" "$GREEN"
    print_msg "   数据库: $DB_NAME" "$BLUE"
    print_msg "   表数量: $TABLE_COUNT 张" "$BLUE"
}

# 编译后端
build_backend() {
    print_title "🔨 编译后端"
    
    if ! command -v mvn &> /dev/null; then
        print_msg "❌ Maven未安装" "$RED"
        return 1
    fi
    
    print_msg "正在Maven编译打包..." "$BLUE"
    mvn clean package -DskipTests
    
    if [ ! -f "ruoyi-admin/target/$APP_NAME" ]; then
        print_msg "❌ 编译失败" "$RED"
        return 1
    fi
    
    cp ruoyi-admin/target/$APP_NAME .
    print_msg "✅ 后端编译完成！" "$GREEN"
}

# 构建前端
build_frontend() {
    print_title "🎨 构建前端"
    
    if [ ! -d "ruoyi-ui" ]; then
        print_msg "❌ 前端目录不存在" "$RED"
        return 1
    fi
    
    cd ruoyi-ui
    
    if ! command -v npm &> /dev/null; then
        print_msg "❌ npm未安装" "$RED"
        cd ..
        return 1
    fi
    
    print_msg "正在安装依赖..." "$BLUE"
    npm install --silent
    
    print_msg "正在构建..." "$BLUE"
    npm run build:prod
    
    cd ..
    
    if [ ! -d "ruoyi-ui/dist" ]; then
        print_msg "❌ 构建失败" "$RED"
        return 1
    fi
    
    print_msg "✅ 前端构建完成！" "$GREEN"
}

# 启动后端
start_backend() {
    print_title "▶️  启动后端"
    
    PID=$(ps -ef | grep java | grep $APP_NAME | grep -v grep | awk '{print $2}')
    if [ -n "$PID" ]; then
        print_msg "⚠️  后端已在运行中 (PID: $PID)" "$YELLOW"
        return 0
    fi
    
    if [ ! -f "$APP_NAME" ]; then
        print_msg "❌ jar包不存在，请先编译" "$RED"
        return 1
    fi
    
    mkdir -p logs
    nohup java -jar $APP_NAME > logs/$APP_NAME.log 2>&1 &
    
    print_msg "正在启动..." "$BLUE"
    sleep 3
    
    PID=$(ps -ef | grep java | grep $APP_NAME | grep -v grep | awk '{print $2}')
    if [ -n "$PID" ]; then
        print_msg "✅ 后端启动成功！" "$GREEN"
        print_msg "   进程ID: $PID" "$BLUE"
        print_msg "   端口: $APP_PORT" "$BLUE"
        print_msg "   日志: logs/$APP_NAME.log" "$BLUE"
    else
        print_msg "❌ 启动失败，请查看日志" "$RED"
        return 1
    fi
}

# 停止后端
stop_backend() {
    print_title "⏸️  停止后端"
    
    PID=$(ps -ef | grep java | grep $APP_NAME | grep -v grep | awk '{print $2}')
    if [ -z "$PID" ]; then
        print_msg "ℹ️  后端未运行" "$BLUE"
        return 0
    fi
    
    print_msg "正在停止 (PID: $PID)..." "$BLUE"
    kill -15 $PID
    
    # 等待进程结束
    for i in {1..30}; do
        if ! ps -p $PID > /dev/null 2>&1; then
            print_msg "✅ 后端已停止" "$GREEN"
            return 0
        fi
        sleep 1
    done
    
    # 强制停止
    print_msg "⚠️  强制停止..." "$YELLOW"
    kill -9 $PID
    print_msg "✅ 后端已停止" "$GREEN"
}

# 重启后端
restart_backend() {
    stop_backend
    sleep 2
    start_backend
}

# 查看日志
view_logs() {
    print_title "📝 查看日志"
    
    if [ ! -f "logs/$APP_NAME.log" ]; then
        print_msg "❌ 日志文件不存在" "$RED"
        return 1
    fi
    
    print_msg "最近50行日志：" "$BLUE"
    echo "========================================="
    tail -n 50 logs/$APP_NAME.log
    echo "========================================="
    echo ""
    print_msg "实时日志: tail -f logs/$APP_NAME.log" "$YELLOW"
}

# 测试系统
test_system() {
    print_title "🧪 测试系统"
    
    print_msg "检查后端服务..." "$BLUE"
    PID=$(ps -ef | grep java | grep $APP_NAME | grep -v grep | awk '{print $2}')
    if [ -n "$PID" ]; then
        print_msg "  ✅ 后端运行中 (PID: $PID)" "$GREEN"
    else
        print_msg "  ❌ 后端未运行" "$RED"
    fi
    
    print_msg "检查端口监听..." "$BLUE"
    if netstat -tuln 2>/dev/null | grep -q ":$APP_PORT "; then
        print_msg "  ✅ 端口 $APP_PORT 已监听" "$GREEN"
    else
        print_msg "  ❌ 端口 $APP_PORT 未监听" "$RED"
    fi
    
    print_msg "检查HTTP响应..." "$BLUE"
    if curl -s http://localhost:$APP_PORT > /dev/null 2>&1; then
        print_msg "  ✅ HTTP服务正常" "$GREEN"
    else
        print_msg "  ⚠️  HTTP服务无响应" "$YELLOW"
    fi
    
    print_msg "检查数据库..." "$BLUE"
    if check_mysql; then
        TABLE_COUNT=$(mysql -h localhost -u"$DB_USER" -p"$DB_PASS" "$DB_NAME" \
            -e "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='$DB_NAME';" \
            2>/dev/null | tail -n 1)
        print_msg "  ✅ 数据库连接正常 ($TABLE_COUNT 张表)" "$GREEN"
    else
        print_msg "  ❌ 数据库连接失败" "$RED"
    fi
}

# 一键部署
deploy_all() {
    print_title "🚀 一键部署"
    
    print_msg "开始完整部署..." "$CYAN"
    echo ""
    
    # 1. 数据库
    print_msg "📊 步骤 1/4: 初始化数据库" "$CYAN"
    if init_database; then
        print_msg "✅ 数据库初始化完成" "$GREEN"
    else
        print_msg "❌ 数据库初始化失败" "$RED"
        return 1
    fi
    echo ""
    
    # 2. 编译后端
    print_msg "🔨 步骤 2/4: 编译后端" "$CYAN"
    if build_backend; then
        print_msg "✅ 后端编译完成" "$GREEN"
    else
        print_msg "❌ 后端编译失败" "$RED"
        return 1
    fi
    echo ""
    
    # 3. 构建前端
    print_msg "🎨 步骤 3/4: 构建前端" "$CYAN"
    if build_frontend; then
        print_msg "✅ 前端构建完成" "$GREEN"
    else
        print_msg "⚠️  前端构建失败（继续）" "$YELLOW"
    fi
    echo ""
    
    # 4. 启动服务
    print_msg "▶️  步骤 4/4: 启动服务" "$CYAN"
    if start_backend; then
        print_msg "✅ 服务启动完成" "$GREEN"
    else
        print_msg "❌ 服务启动失败" "$RED"
        return 1
    fi
    echo ""
    
    # 显示结果
    print_title "🎉 部署完成"
    print_msg "系统信息：" "$BLUE"
    print_msg "  • 后端地址: http://localhost:$APP_PORT" "$CYAN"
    print_msg "  • 前端地址: http://localhost" "$CYAN"
    print_msg "  • 默认账号: admin / admin123" "$CYAN"
    echo ""
    print_msg "管理命令：" "$BLUE"
    print_msg "  • 启动: ./start.sh (选择5)" "$CYAN"
    print_msg "  • 停止: ./start.sh (选择6)" "$CYAN"
    print_msg "  • 日志: ./start.sh (选择8)" "$CYAN"
}

# 主循环
main() {
    while true; do
        show_menu
        read -p "请输入选项 [0-9]: " choice
        
        case $choice in
            1) deploy_all ;;
            2) init_database ;;
            3) build_backend ;;
            4) build_frontend ;;
            5) start_backend ;;
            6) stop_backend ;;
            7) restart_backend ;;
            8) view_logs ;;
            9) test_system ;;
            0) 
                print_msg "👋 再见！" "$GREEN"
                exit 0
                ;;
            *)
                print_msg "❌ 无效选项" "$RED"
                ;;
        esac
        
        echo ""
        read -p "按回车键继续..." 
    done
}

# 运行主程序
main

